<?PHP
	// *******************************************************************************************
	// @Namespace : Colibri.Core
	// @Description : Containes helper methods to map URL's in modules.
	// @Author : Ronald Guillen
	// *******************************************************************************************
	
	class Urls
	{
		public $Patterns = Array();
		
		private $RequestUrl = NULL;
		private $PatternUrl = NULL;
		private $RawUrl = NULL;
		private $Params = Array();
		
		function  __construct()
		{
			$this->RawUrl = $_SERVER["REQUEST_URI"];
			$this->RequestUrl = $this->parseUrlElements($this->RawUrl);
		}
		
		// @ Methods
		function addPattern($pattern = NULL)
		{
			array_push($this->Patterns, $pattern);
		}
		
		function getRequest()
		{
			$currentRequest = new UrlRequest();
			
			for($n = 0; $n < count($this->Patterns); $n++)
			{
				foreach($this->Patterns[$n]->Collection as $key => $value)
				{
					$this->PatternUrl = $this->parseUrlElements($key);
					
					if($this->compareUrlPattern($this->RequestUrl, $this->PatternUrl))
					{
						$currentRequest->Container = $this->Patterns[$n]->Container;
						$currentRequest->View = $value;
						$currentRequest->Params = $this->Params;
					}
				}
			}
			
			return $currentRequest;
		}
		
		// @ Helpers
		
		function compareUrlPattern($request, $pattern)
		{
			$this->Params = Array();
			
			$requestCount = count($request);
			$patternCount = count($pattern);
			$matchStatus = false;
			
			if($patternCount == $requestCount)
			{
				for($n = 0; $n < $requestCount; $n++)
				{
					if($pattern[$n] != "{*}")
					{
						if($request[$n] == $pattern[$n])
						{
							$matchStatus = true;
						}
						else
						{
							return false;
						}
					}
					else
					{
						array_push($this->Params, $request[$n]);
					}
				}
			}
			else
			{
				return false;
			}
			
			return $matchStatus;
		}
		
		function parseUrlElements($rawUrl)
		{
			$urlElements = ($rawUrl != "/") ? preg_split("/\//", $rawUrl) : Array("/");
			if($rawUrl != "/") { array_shift($urlElements); }
			
			return $urlElements;
		}
	}
	
?>